<?php


namespace App\Http\Controllers\App\V3;


use App\Exceptions\BasicException;
use App\Services\Tools\RedisService;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AppVersionController extends BaseController
{
    public function getAppSetting(Request $request)
    {
        $v = app('validator')->make(
            $request->all(),
            [
                'app_type' => 'numeric|gt:0'
            ]
        );
        if ($v->fails()) throw new BasicException(10010, getValidateMessage($v->messages()));

        $app_type = $request->input('app_type', 2);
        $android_application_type = $request->input('android_application_type', 0);
        $version = $request->input('version', 0);
        $result = app('repo_app_version')->getAppSetting($app_type, $android_application_type, $version);

        return Response::sendData($result);
    }

    public function getVersionInfo(Request $request)
    {
        $v = app('validator')->make(
            $request->all(),
            [
                'app_type' => 'numeric|gt:0'
            ]
        );
        if ($v->fails()) throw new BasicException(10010, getValidateMessage($v->messages()));

        $app_type = $request->input('app_type', 2);
        $android_application_type = $request->input('android_application_type', 0);
        $version = $request->input('version', 0);
        $app_version = str_replace('.', '', $request->header('appVersion'));
        $result['version_info'] = app('repo_app_version')->getVersionInfo($app_type, $android_application_type, $version);
        $result['app_setting'] = app('repo_app_version')->getAppSetting($app_type, $android_application_type, $version);
        $result['is_update'] = 0;
        if (empty($result['app_setting']) || empty($result['version_info'])) {
            return Response::sendData($result, '返回成功');
        }
        // 判断版本是否需要更新
        $userId = UID;
        $backgroundKey = 'act:room:background:pop_type:' . $result['version_info']['pop_type'] . ':user_id:' . $userId;
        if ($app_version < str_replace('.', '', $result['version_info']['version'])) {
            // 判断自主更新方式 本次是否需要更新
            if ($result['version_info']['update_type'] == 2) {
                $catchValue = app('redis')->get($backgroundKey);
                if (empty($catchValue)) {
                    $result['is_update'] = 1;
                    switch ($result['version_info']['pop_type']) {
                        case 2:
                            $tomorrow = strtotime(date('Y-m-d', strtotime('+1day')));
                            app('redis')->setex($backgroundKey, $tomorrow - time(), $result['version_info']['pop_type']);
                            break;
                        case 3:
                            $next_week = strtotime(date('Y-m-d', strtotime('+7day')));
                            app('redis')->setex($backgroundKey, $next_week - time(), $result['version_info']['pop_type']);
                            break;
                    }
                } else {
                    $result['is_update'] = 0;
                }
            } else {
                $result['is_update'] = 1;
            }
        }

        //查询用户是否在注册后第二/三/七/十五日登录
        $userInfo = app('model_user')
            ->select('register_time', 'channel_stage_id')
            ->where('user_id', UID)
            ->first();
        $userRegisterDate = date('Y-m-d', $userInfo->register_time);
        $days = round((strtotime(date('Y-m-d')) - strtotime($userRegisterDate)) / 86400) + 1;
        switch ($days) {
            case 2:
                $field = 'is_next_day_login';
                break;
            case 3:
                $field = 'is_third_day_login';
                break;
            case 7:
                $field = 'is_seven_day_login';
                break;
            case 15:
                $field = 'is_fifteen_day_login';
                break;
            case 30:
                $field = 'is_thirtieth_day_login';
                break;
            default:
                $field = '';
        }
        if ($field) {
            $userLoginDate = app('model_user_login_date')->select('user_id')->where('user_id', UID)->first();
            if ($userLoginDate) {
                app('model_user_login_date')->where('user_id', UID)->update([$field => 1]);
            } else {
                app('model_user_login_date')->insert([
                    'user_id' => UID,
                    'channel_stage_id' => $userInfo->channel_stage_id,
                    $field => 1,
                ]);
            }
        }

        //维护最新登录时间
        app('model_user')->where('user_id', UID)->update(['last_login_time' => time()]);

        return Response::sendData($result, '返回成功');
    }

    public function getUpdateInfo(Request $request)
    {
        $appVersion = $request->header('appVersion');
        $clientType = $request->header('clientType');
        if (!$appVersion || !$clientType) {
            throw new BasicException(-1, '非法请求');
        }
        $appType = $clientType == 'android' ? 1 : 2;
        $versionInfo = app('model_version_management')->where('app_type', $appType)->orderBy('id', 'desc')->first();
        $result = ['is_update' => 0, 'is_force' => 0, 'info' => null];
        if ($versionInfo) {
            if (version_compare($appVersion, $versionInfo->version, '<')) {
                $result['is_update'] = 1;
                $result['is_force'] = $versionInfo->update_type == 1 ? 1 : 0;
                $result['info']['version'] = $versionInfo->version;
                $result['info']['type'] = $versionInfo->install_type; // 安装方式 1 上传安装包  2填写下载链接 3iOS安装地址
                $result['info']['url'] = $versionInfo->install_url; // 安装地址
                $result['info']['content'] = $versionInfo->update_content; // 安装文案
            }
        }
        return Response::sendData($result, '更新结果');

//        $where['version_status'] = 1;
//        if ($deviceInfo->client_type == 'android') {
//            $where['app_type'] = 1;
//        } else {
//            $where['app_type'] = 2;
//        }
//        $versionInfo = app('model_version_management')->where($where)->orderBy('id', 'desc')->first()->toArray();
//        $versionInfo = app('model_version_management')->where($where)->orderBy('id', 'desc')->first();
//        $backgroundKey = 'act:room:background:pop_type:' . $versionInfo['pop_type'].':user_id:'.$userId;
//        // 返回结果
//        $result = [];
        // 计算用户是否需要返回更新模式
//        if ($deviceInfo->app_version != $versionInfo['version']) {
//            // 判断自主更新方式 本次是否需要更新
//            if ($versionInfo['update_type'] == 2) {
//                $catchValue = app('redis')->get($backgroundKey);
//                if (empty($catchValue)) {
//                    $result['is_update'] = 1;
//                    switch ($versionInfo['pop_type']) {
//                        case 2:
//                            $tomorrow = strtotime(date('Y-m-d',strtotime('+1day')));
//                            app('redis')->setex($backgroundKey, $tomorrow-time(),$versionInfo['pop_type']);
//                            break;
//                        case 3:
//                            $next_week = strtotime(date('Y-m-d',strtotime('+7day')));
//                            app('redis')->setex($backgroundKey, $next_week-time(),$versionInfo['pop_type']);
//                            break;
//                    }
//                } else {
//                    $result['is_update'] = 0;
//                }
//            }
//        }
        return Response::sendData($versionInfo, '更新结果');
    }
}
